package com.bocloud.kong.service.impl;

import static org.apache.commons.lang3.StringUtils.isBlank;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bocloud.kong.client.PluginClient;
import com.bocloud.kong.model.Plugin;
import com.bocloud.kong.service.PluginService;
import com.bocloud.model.Result;
import com.bocloud.utils.Asserts;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

/**
 * Title: PluginServiceImpl Description:
 *
 * @author lkx
 * @version 1.0.0
 * @since 2017-02-15 17:51
 */
@Service
public class PluginServiceImpl implements PluginService {

	private static Logger logger = LoggerFactory.getLogger(PluginServiceImpl.class);

	@Autowired
	private PluginClient pluginClient;

	@Override
	public List<String> queryEnabledPlugins() {
		try {
			return pluginClient.enabledPlugins();
		} catch (IOException e) {
			logger.info("", e);
			return Lists.newArrayList();
		}
	}

	@Override
	public Plugin queryOAuth2Plugin(String apiId) {
		try {
			Preconditions.checkNotNull(apiId, "API ID 不能为空");
			return pluginClient.querySpecificApiAndPlugin(apiId, "oauth2");
		} catch (IOException e) {
			logger.info("", e);
			return null;
		}
	}

	@Override
	public Result saveOAuth2Plugin(String apiId, Plugin plugin) {
		Asserts.checkNotBlank(apiId, "待保存插件对应的 API ID 不能为空.");
		Plugin newPlugin;
		try {
			if (isBlank(plugin.getId())) {
				newPlugin = pluginClient.add(apiId, plugin);
			} else {
				newPlugin = pluginClient.update(plugin.getId(), plugin);
			}
		} catch (IOException e) {
			logger.info("", e);
			return new Result(false, e.getMessage());
		}
		if (newPlugin != null) {
			return new Result(true, "插件保存成功" + newPlugin.toString());
		}
		return new Result(false, "插件信息保存失败");
	}

	@Override
	public List<Plugin> queryAll(Plugin plugin) {
		Plugin queryPlugin = plugin == null ? new Plugin() : plugin;
		queryPlugin.setSize(getPluginAmount(queryPlugin));
		try {
			return pluginClient.query(queryPlugin);
		} catch (IOException e) {
			logger.info("", e);
		}
		return Lists.newArrayList();
	}

	private Integer getPluginAmount(Plugin plugin) {
		try {
			Plugin queryPlugin = plugin == null ? new Plugin() : plugin;
			queryPlugin.setSize(1);
			return pluginClient.totalSize(queryPlugin);
		} catch (IOException e) {
			logger.info("", e);
		}
		return null;
	}
}
